﻿using SIE.SCADA.UICommon.Controls;
using SIE.SCADA.UICommon.Controls.TabControlTabItems;
using SIE.SCADA.UICommon.Interfaces;
using SIE.SCADA.UICommon.UIAttribute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;
using System.Xml.Linq;
using SIE.SCADA.Common;
using SIE.SCADA.Common.PlugIn;
using SIE.SCADA.Common.Command;
using SIE.SCADA.Common.Repository;
using SIE.SCADA.ZemtDemo.View;
using SIE.SCADA.ZemtDemo.Machines;
using System.Windows;
using SCADA_DAQ.ZEMT.Server;
using System.Threading.Tasks;
using Models;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.ZemtDemo.Common;

namespace SIE.SCADA.ZemtDemo
{
    [RunnerConfigName("Menus")]
    public class ZemtDemoServer : Runner
    {
        //MainCustWindow MainCustWindow;
        private PlanManager planManager;
        private WoInfoManager woInfoManager;
        private EquipManager equipManager;
        private EmployManager employManager;
        private EquipmentDataManager equipmentDataManager;
        List<IBaseMachine> machines = new List<IBaseMachine>();
        private CustomContainer CustomContainer { get; set; }
        
        public List<UserNotifyIconMenu> Menus { get; set; }


        public override string ClassType
        {
            get => typeof(ZemtDemoServer).FullName + "," + typeof(ZemtDemoServer).Assembly.ManifestModule.Name;
            set { }
        }
        public override bool Init()
        {
            var vcommand = new ZemtDemoCommand();
            Command = vcommand;
            Menus = new List<UserNotifyIconMenu>()
            {
                new UserNotifyIconMenu(){
                    Command=new UICommand((o)=>{
                       if(o[0] is  System.Windows.Forms.MenuItem  menuItem)
                        {
                            CreateCustomContainer("铁科扭力扳手采集系统");
                            //CustomContainer.AddChild("StationView",new MainCustWindow(){ FontSize=16});
                            Login();
                        }
                       return null;
                    },
                    ()=>true,
                    null,
                    "扭力扳手采集系统")
                }
            };
            return true;
        }
        public void Login() {
            if (CustomContainer == null) return;
            var Login = new LoginView(this);
            CustomContainer.AddChild("登录", Login);
        }



        public void InitTab(string rolelist)
        {

            foreach (var item in Env.Machines)
            {
                var machine = item.Value;
                var hmi = new StationView(machine);
                CustomContainer.AddChild(machine.BaseProtocol.DeviceDesc, hmi);
            }
            var equip = new EquipmentView();
            var manual = new ManualView();
            var workInfo = new WorkInfoView();
            var prodInfo = new ProdInfoView();
            var subProcess = new SubProcessView();
            var Pathroute = new PathrouteView();
            var TurqueRecord = new TurqueRecordView();
            var JobRecord = new JobRecordView();
            var MatProductRelation = new MatProductRelationView();
            var Employee = new EmployeeView();
            var UserRole = new UserRoleView();

            string[] roleArry= rolelist.Split(',');

            for (int i=0; i< roleArry.Length;i++) {

                if (roleArry[i]== "扭力记录") {
                    CustomContainer.AddChild("扭力记录", TurqueRecord);
                }
                if (roleArry[i] == "扭力报表")
                {
                    CustomContainer.AddChild("扭力报表", JobRecord);
                }
                if (roleArry[i] == "工件管理")
                {
                    CustomContainer.AddChild("工件管理", prodInfo);
                }
                if (roleArry[i] == "物料管理")
                {
                    CustomContainer.AddChild("物料管理", MatProductRelation);
                }
                if (roleArry[i] == "设备管理")
                {
                    CustomContainer.AddChild("设备管理", equip);
                }
                if (roleArry[i] == "工艺管理")
                {
                    CustomContainer.AddChild("工艺管理", subProcess);
                }
                if (roleArry[i] == "人员管理")
                {
                    CustomContainer.AddChild("人员管理", Employee);
                }
                if (roleArry[i]== "权限管理") {
                    CustomContainer.AddChild("权限管理", UserRole);
                }
            }

            
           










            //if (CustomContainer == null) return;
            //if (name == "User") { 

            //    foreach (var item in Env.Machines)
            //    {
            //        var machine = item.Value;
            //        var hmi = new StationView(machine);
            //        CustomContainer.AddChild(machine.BaseProtocol.DeviceDesc, hmi);
            //    }
            //    var TurqueRecord = new TurqueRecordView();
            //    var JobRecord = new JobRecordView();
            //    var prodInfo = new ProdInfoView();

            //    CustomContainer.AddChild("扭力记录", TurqueRecord);
            //    CustomContainer.AddChild("扭力报表", JobRecord);
            //    CustomContainer.AddChild("工件管理", prodInfo);

            //}
            //else if(name == "Admin"){
            //    foreach (var item in Env.Machines)
            //    {
            //        var machine = item.Value;
            //        var hmi = new StationView(machine);
            //        CustomContainer.AddChild(machine.BaseProtocol.DeviceDesc, hmi);
            //    }
            //    var equip = new EquipmentView();
            //    var manual = new ManualView();
            //    var workInfo = new WorkInfoView();
            //    var prodInfo = new ProdInfoView();
            //    var subProcess = new SubProcessView();
            //    var Pathroute = new PathrouteView();
            //    var TurqueRecord = new TurqueRecordView();
            //    var JobRecord = new JobRecordView();
            //    var MatProductRelation = new MatProductRelationView();
            //    var Employee = new EmployeeView();
            //    var UserRole = new UserRoleView();


            //    CustomContainer.AddChild("扭力记录", TurqueRecord);
            //    CustomContainer.AddChild("扭力报表", JobRecord);
            //    CustomContainer.AddChild("工件管理", prodInfo);
            //    //CustomContainer.AddChild("工单管理", workInfo);
            //    CustomContainer.AddChild("物料管理", MatProductRelation);
            //    CustomContainer.AddChild("设备管理", equip);
            //    CustomContainer.AddChild("工艺管理", subProcess);
            //    CustomContainer.AddChild("人员管理", Employee);
            //    //CustomContainer.AddChild("工艺路线", Pathroute);
            //    CustomContainer.AddChild("权限管理", UserRole);
            //}
        }

        private void CreateCustomContainer(string title)
        {
            if (CustomContainer == null)
            {
                CustomContainer = new CustomContainer
                {
                    Title = title
                };
                CustomContainer.Closed += CustomContainer_Closed;
            }
        }
        private void CustomContainer_Closed(object sender, EventArgs e)
        {
            CustomContainer.Closed -= CustomContainer_Closed;
            CustomContainer = null;
        }

        public override bool Load(string fileName)
        {
            FileName = fileName;
            Repository = new JsonRepository(FileName);
            Repository.Load(typeof(UserNotifyIconMenu));
            Menus = (Repository.Model as List<UserNotifyIconMenu>) ?? new List<UserNotifyIconMenu>();

            return true;
        }

        public override bool Save()
        {
            return SaveAs(FileName);
        }

        public override bool SaveAs(string fileName)
        {
            return true;
        }

        private void MqInit()
        {
            var task = Task.Factory.StartNew(() =>
            {
                //planManager = PlanManager.CreateInstance();
                //planManager.Start();
                //woInfoManager = WoInfoManager.CreateInstance();
                //woInfoManager.Start();


                equipManager = EquipManager.CreateInstance();
                equipManager.Start();
                employManager = EmployManager.CreateInstance();
                employManager.Start();
                equipmentDataManager = EquipmentDataManager.CreateInstance();
                equipmentDataManager.Start();

            });
        }

        public override bool Start()
        {
            new AccessWorker();
            MqInit();
            machines = new List<IBaseMachine>();

            XDocument xDocument = XDocument.Load(Env.DeviceCfgFile);
            var node = xDocument.Descendants("Devices");
            List<DeviceItem> deviceCfgs = Util.Deserialize<Devices>(node.FirstOrDefault().ToString()).Items;
            var devices = deviceCfgs.Where(t => t.IsEnable == true);
            List<Type> types = Assembly.GetExecutingAssembly().GetTypes().ToList();
            foreach (var item in devices)
            {
                string deviceTypeName = item.DeviceType;             //
                Type type = types.Where(t => t.Name == deviceTypeName).FirstOrDefault();
                if (type != null)
                {
                    //Type：TorqueWrench
                    var m = Activator.CreateInstance(type, item.DeviceID);
                    if(m is IBaseMachine machine)
                    {
                        machines.Add(machine);
                    }
                }
            }
            return true;
        }

        public override bool Stop()
        {
            try
            {
                CustomContainer?.Close();
            }
            catch (Exception)
            {
            }
            return true;
        }


        public override bool Exit()
        {
            return true;
        }

    }
}
